package com.dwxt.sport.service;

import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.Page;
import com.dwxt.common.constant.VariableConstants;
import com.dwxt.common.util.JsonUtils;
import com.dwxt.sport.dao.DeviceSceneMapper;
import com.dwxt.sport.dao.SceneMapper;
import com.dwxt.sport.entity.DeviceScene;
import com.dwxt.sport.entity.Scene;
import com.dwxt.sport.entity.WifeDevice;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SceneService {
    @Autowired
    private SceneMapper sceneMapper;

    @Autowired
    private DeviceSceneMapper deviceSceneMapper;

    @Autowired
    private WifeDeviceService wifeDeviceService;


    public List<Scene> selectAllScene() {
        return sceneMapper.selectAll();
    }

    public List<Scene> selectByDeviceIdList(List<String> deviceIdList) {
        List<DeviceScene> deviceSceneList = selectDeviceScenesByDeviceIdList(deviceIdList);
        return selectByIds(deviceSceneList.stream().map(DeviceScene::getSceneId).collect(Collectors.toList()));
    }

    public List<DeviceScene> selectDeviceScenesByDeviceIdList(List<String> deviceIdList) {
        Example example = new Example(DeviceScene.class);
        example.createCriteria().andIn("deviceId", deviceIdList);
        return deviceSceneMapper.selectByExample(example);
    }

    public List<Scene> selectByIds(List<String> ids) {
        Example example = new Example(Scene.class);
        example.createCriteria().andIn("id", ids);
        return sceneMapper.selectByExample(example);
    }

    public BaseResult selectWifiScenePage(Page page) {
        List<WifeDevice> wifeDeviceList = wifeDeviceService.selectByType(1);
        List<DeviceScene> deviceSceneList = selectDeviceScenesByDeviceIdList(wifeDeviceList.stream().map(WifeDevice::getId).collect(Collectors.toList()));

        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<Scene> scenes = selectByIds(deviceSceneList.stream().map(DeviceScene::getSceneId).collect(Collectors.toList()));
        PageInfo pageInfo = new PageInfo<>(scenes);
        List<Object> classification = scenes.stream().map(scene -> {

            Map map = JsonUtils.jsonToPojo(JsonUtils.objectToJson(scene), Map.class);
            map.put("classification",
                    VariableConstants.STRING_CONSTANT_1);
            return map;
        }).collect(Collectors.toList());
        pageInfo.setList(classification);
        return BaseResult.ok(pageInfo);
    }
}
